import { extend, ResponseError } from 'umi-request';
import weui from 'weui.js';
import { getToken } from './auth';

// const prefix = '/api/pay';
// const prefix = 'https://user-api.sssplus.cn';
// const prefix = "http://172.16.3.16:10010"
// const prefix = "http://192.168.1.128:10010"
// const prefix = "http://172.16.3.16:8083"
// const prefix = "http://192.168.1.128:8083/pay"
// const prefix = 'https://admin.sssplus.cn/api/pay';
const prefix = 'http://hhweb.vaiwan.cn/api';

const errorHandler = function (error: ResponseError) {
  const codeMap: {
    [key: string]: string;
  } = {
    '021': 'An error has occurred',
    '022': 'It’s a big mistake,',
    // ....
  };
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    console.log(error.response.status);
    console.log(error.response.headers);
    console.log(error.data);
    console.log(error.request);
    console.log(codeMap[error.data.status]);
  } else {
    // The request was made but no response was received or error occurs when setting up the request.
    console.log(error.message);
  }

  throw error; // If throw. The error will continue to be thrown.

  // return {some: 'data'}; If return, return the value as a return. If you don't write it is equivalent to return undefined, you can judge whether the response has a value when processing the result.
  // return {some: 'data'};
};

const request = extend({
  prefix: prefix,
  timeout: 60000,
  timeoutMessage: '当前网络不可用，请检查你的网络设置',
  errorHandler: errorHandler,
  // requestType: "form",
  //   headers: {
  //     'Content-Type': 'multipart/form-data',
  //   },
});

request.interceptors.request.use((url, options) => {
  // console.log(options);
  // 将 token 添加至请求头 X-Auth-Token 中
  // options.headers['X-Auth-Token'] = getToken()
  return {
    url: url,
    options: { ...options, interceptors: true },
  };
});

// handling error in response interceptor
request.interceptors.response.use(async (response) => {
  const codeMaps: {
    [key: number]: string;
  } = {
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
  };
  if (200 != response.status) {
    console.log('interceptors response: ', response);

    weui.topTips(codeMaps[response.status] || '服务不可用');
    return response;
  }
  const data = await response.clone().json();
  // console.log(data, response);

  if (0 != data.code) {
    weui.topTips(data.msg || data.message);
    return Promise.reject(response);
  }

  if (response.headers.get('X-Auth-Token')) {
    return Promise.resolve({
      token: response.headers.get('X-Auth-Token'),
      ...data,
    });
  }

  return response;
});

export default request;
